// package-market/pages/lottery-edit/index.js
const app = getApp();
import { PACKAGE_MARKET_PAGE } from '../../../constants/route';
import { ManageTargetInfoUpdateMixins, ManageTargetExchangeMixins } from '../../../behaviors/page';
import { navToAction, navBack, tipToast, showLoading, hideLoading, redirectTo } from '../../../common/env';
import { obj2Arr, arr2Obj, formatDate, getDateTS, deepClone, isValidPhone, isValidTel } from '../../../common/utils';
import { TipDialog } from '../../../common/tip';
import { dealLotteryDefaultData, getProbability, getFrequency } from '../../biztools/lottery';
import { TARGET_TYPE } from '../../../constants/common';
import { ACTIVITY_STATUS_VALUE } from '../../../constants/activity';
import { LOTTERY_ACTIVITY_TYPE_NAME, LOTTERY_WIN_RATE, LOTTERY_WIN_RATE_NAME, LOTTERY_ACTIVITY_TYPE_RULE } from '../../constants/lottery';
import { getLotteryActivity, editLotteryActivity } from '../../api/lottery';
let brandId, activityId, copySourceId;
let activityProductWithSkusCache;

Page({
    mixins: [ManageTargetInfoUpdateMixins, ManageTargetExchangeMixins],
    data: {
        LOTTERY_ACTIVITY_TYPE_RULE,
        activityInfo: {},
        modifyFlag: true,
        lotteryTypePopup: {
            show: false,
            columns: obj2Arr(LOTTERY_ACTIVITY_TYPE_NAME),
            map: LOTTERY_ACTIVITY_TYPE_NAME,
        },
        winRatePopup: {
            show: false,
            columns: obj2Arr(LOTTERY_WIN_RATE_NAME),
            map: LOTTERY_WIN_RATE_NAME,
        },
        frequencyPopup: {
            show: false,
            columns: getFrequency(),
            map: arr2Obj(getFrequency(), 'value', 'name'),
        },
        startDatePickerPopup: {
            show: false,
            minDate: Date.now(),
            dateStr: '',
        },
        endDatePickerPopup: {
            show: false,
            dateStr: '',
            minDate: getDateTS('', false, 'minute') + 5 * 60 * 1000
        },
        telModal: {
            show: false,
        },
    },
    async onLoad(options) {
        brandId = options.brandId;
        activityId = options.activityId;
        copySourceId = options.copySourceId;
        await this._handleExchange(TARGET_TYPE.brand, brandId);
        await this._handleGetDetail();
        app.event.addListener('getLotteryActivityInfo', this._handleGetActivityInfo.bind(this));
    },
    onUnload() {
        app.event.removeListener('getLotteryActivityInfo');
    },
    _handleGetActivityInfo(activityInfo) {
        delete activityInfo.activityProductWithSkusCache;
        this.setData({ activityInfo });
    },
    async _handleGetDetail() {
        showLoading('加载中...');
        const { manageTargetInfo } = this.data;
        const dealActivityInfo = dealLotteryDefaultData(manageTargetInfo);
        let activityInfo;
        if (activityId) {
            activityInfo = await getLotteryActivity({ brandId, activityId });
            activityProductWithSkusCache = deepClone(activityInfo).activityProductWithSkus;
        } else if (copySourceId) {
            activityInfo = await getLotteryActivity({ brandId, activityId: copySourceId, isCopy: true, });
            activityInfo.begined = dealActivityInfo.begined;
            activityInfo.ended = dealActivityInfo.ended;
            delete activityInfo.activityId;
            delete activityInfo.processStatus;
        } else {
            activityInfo = dealActivityInfo;
        }
        const modifyFlag = !activityInfo.processStatus || activityInfo.processStatus === ACTIVITY_STATUS_VALUE.draft;
        this.setData({
            modifyFlag,
            activityInfo,
            'startDatePickerPopup.dateStr': formatDate(activityInfo.begined, 'YYYY年MM月DD日 HH:mm'),
            'endDatePickerPopup.dateStr': formatDate(activityInfo.ended, 'YYYY年MM月DD日 HH:mm'),
        });
        hideLoading();
    },
    handleChangeLotteryType(e) {
        const { value } = e.detail.value;
        this.setData({
            'activityInfo.lottery1.uiType': value,
        });
    },
    handleChangeWinRate(e) {
        const { value } = e.detail.value;
        const { lottery1, activityProductWithSkus } = this.data.activityInfo;
        lottery1.winRate = value;
        if (lottery1.winRate != LOTTERY_WIN_RATE.custom) {
            lottery1.prizeRates = getProbability(lottery1.winRate, activityProductWithSkus.length);
        }
        this.setData({
            'activityInfo.lottery1': lottery1,
        });
    },
    handleChangeFrequency(e) {
        const { value } = e.detail.value;
        this.setData({
            'activityInfo.maxiumPurchaseFrequency': value,
        });
    },
    handleChangeStartDate(e) {
        const value = getDateTS(e.detail, false, 'minute');
        this.setData({
            'activityInfo.begined': value,
            'startDatePickerPopup.dateStr': formatDate(value, 'YYYY年MM月DD日 HH:mm'),
        });
    },
    handleChangeEndDate(e) {
        const value = getDateTS(e.detail, false, 'minute');
        this.setData({
            'activityInfo.ended': value,
            'endDatePickerPopup.dateStr': formatDate(value, 'YYYY年MM月DD日 HH:mm'),
        });
    },
    handleChangeTel(e) {
        this.setData({
            'activityInfo.tel': e.detail,
        });
    },
    handleChangeActivityInfo(e) {
        const activityInfo = e.detail;
        this.setData({ activityInfo });
    },
    handleShowLotteryTypePopup() {
        if (!this.data.modifyFlag) {
            tipToast('活动已发布，此项不能编辑');
            return;
        }
        this.setData({
            'lotteryTypePopup.show': true,
        });
    },
    handleShowWinRatePopup() {
        if (!this.data.modifyFlag) {
            tipToast('活动已发布，此项不能编辑');
            return;
        }
        this.setData({
            'winRatePopup.show': true,
        });
    },
    handleShowFrequencyPopup() {
        this.setData({
            'frequencyPopup.show': true,
        });
    },
    handleShowStartDatePickerPopup() {
        if (!this.data.modifyFlag) {
            tipToast('活动已发布，此项不能编辑');
            return;
        }
        this.setData({
            'startDatePickerPopup.show': true,
        });
    },
    handleShowEndDatePickerPopup() {
        this.setData({
            'endDatePickerPopup.show': true,
        });
    },
    handleShowTelModal() {
        this.setData({
            'telModal.show': true,
        });
    },
    handleNavTo(e) {
        const { pageName, ...urlParams } = e.currentTarget ? e.currentTarget.dataset : e;
        const { activityInfo } = this.data;
        navToAction(PACKAGE_MARKET_PAGE[pageName], {
            ...urlParams,
        }, {
            success(res) {
                setTimeout(() => {
                    if (pageName === 'lotteryEditScale') {
                        activityInfo.activityProductWithSkusCache = activityProductWithSkusCache || [];
                    }
                    app.event.trigger('sendLotteryActivityInfo', activityInfo);
                }, 800);
            },
        });
    },
    handleNavToEditProduct() {
        this.handleNavTo({
            pageName: 'lotteryEditProduct',
        });
    },
    handleNavToEditScale(e) {
        const productId = e.detail;
        this.handleNavTo({
            pageName: 'lotteryEditScale',
            productId,
        });
    },
    handleNavBack() {
        TipDialog({
            title: '是否退出编辑',
            message: '退出后，编辑的信息将不被保留。',
            confirmButtonText: '确定退出',
            ok() {
                navBack();
            },
        });
    },
    async handlePreview() {
        let { activityInfo } = this.data;
        const { name, tel, intro, activityProductWithSkus, lottery1, warehouseIds, maxiumPurchaseFrequency } = activityInfo;
        const { min, max } = LOTTERY_ACTIVITY_TYPE_RULE[lottery1.uiType];
        if (!name) {
            tipToast('请输入活动名称');
            return;
        }
        if (!activityProductWithSkus || !activityProductWithSkus.length || activityProductWithSkus.length < min || activityProductWithSkus.length > max) {
            tipToast(`请选择${min}-${max}个奖品`);
            return;
        }
        if (!activityProductWithSkus.every(ps => ps.skus.every(s => s.maximum > 0))) {
            tipToast('库存需大于0');
            return;
        }
        if (!lottery1.prizeRates.every(i => i > 0)) {
            tipToast('请设置完整的中奖概率');
            return;
        }
        if (!warehouseIds.length) {
            tipToast('请选择供货仓');
            return;
        }
        if (maxiumPurchaseFrequency === undefined) {
            tipToast('请设置抽奖次数');
            return;
        }
        if (!tel || (!isValidPhone(tel) && !isValidTel(tel))) {
            tipToast('请设置正确的联系方式');
            return;
        }
        showLoading('保存中...');
        const info = await editLotteryActivity(activityInfo);
        if (info) {
            hideLoading();
            if (activityId && info.processStatus !== ACTIVITY_STATUS_VALUE.draft) {
                navBack();
            } else {
                activityInfo = info;
                this.setData({ activityInfo });
                redirectTo(PACKAGE_MARKET_PAGE['lotteryPreview'], {
                    brandId: brandId || activityInfo.brandId,
                    activityId: activityId || activityInfo.activityId,
                });
            }
        }
    },
})
